// pages/contact/contact.js
const app = getApp()
const api = require('../../utils/api');
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;

/**
 * 初始化数据
 */
function initData(that) {
  inputVal = '';

  // msgList = [{
  //     speaker: 'server',
  //     contentType: 'text',
  //     content: '欢迎来到英雄联盟，敌军还有30秒到达战场，请做好准备！'
  //   },
  //   {
  //     speaker: 'customer',
  //     contentType: 'text',
  //     content: '我怕是走错片场了...'
  //   }
  msgList = [{content: '医生说的话', avatar: '', did: 1, poid: 'aaa', time: '2020-11-13 11:30', isDoc: true}, 
  {content: '用户说的话', avatar: '', did: 1, poid: 'aaa', time: '2020-11-13 11:30', isDoc: false}
  ]
  that.setData({
    msgList,
    inputVal
  })
}


Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: '100vh',
    inputBottom: 0, 
    socketOpen: false,
    sotk: null,
    inputVal: '', 
    doc: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({userInfo: app.globalData.userInfo})
    initData(this);
    var doc_id = options.doctor_id
    api.myGet("/doctor/"+doc_id, null).then(res => {
      var myres = res.data.res
      console.debug(myres)
      this.setData({doc: myres})
    }).catch(err => {
      console.debug(err)
    })
    this.connect()
  },
  onHide(){
    this.closeWebsocket('界面隐藏')
  },

  connect(){
    //开始webSocket
    this.data.sotk = wx.connectSocket({
      url: app.globalData.wsUrl+'/chat/'+app.globalData.openid,
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: "POST",
      success: res => {
        console.log('小程序连接成功：', res);
      },
      fail: err => {
        console.log('出现错误啦！！' + err);
        wx.showToast({
          title: '网络异常！',
        })
      }
    })
    this.webSokcketMethods();
  },
  //发送消息
  send(msg) {
    let that = this;
    if (this.data.socketOpen){
      console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
      this.data.sotk.send({
        data: JSON.stringify(msg)
      }, function (res) {
        console.log('已发送', res)
      })
    }
    
  },
 //关闭连接
  closeWebsocket(str){
    if (socketOpen) {
      this.data.sotk.close(
        {
          code: "1000",
          reason: str,
          success: function () {
            console.log("成功关闭websocket连接");
          }
        }
      )
    }
  },

  //监听指令
  webSokcketMethods(e){
    let that = this;
    this.data.sotk.onOpen(res => {
      this.setData({socketOpen: true})
      console.log('监听 WebSocket 连接打开事件。', res);
    })
    this.data.sotk.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      this.setData({socketOpen: false})
    })
    this.data.sotk.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      this.setData({socketOpen: false})
    })
    this.data.sotk.onMessage(onMessage => {
      var data = JSON.parse(onMessage.data);
      if('link'==data.type){
        return
      }
      msgList.push(data)
      this.setData({msgList: msgList})
      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息',data);
    })
  },


  /**
   * 获取聚焦
   */
  focus: function(e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      inputBottom: keyHeight + 'px'
    })
  },

  //失去聚焦(软键盘消失)
  blur: function(e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })
  },

  /**
   * 发送点击监听
   */
  sendClick: function(e) {
    var msg = {content: this.data.inputVal, avatar: '', did: this.data.doc.id, poid: app.globalData.openid, time: '2020-11-13 11:30', isDoc: false}
    console.debug("sendClick",msg)
    this.send(msg)
    inputVal = '';
    this.setData({
      inputVal
    });
  },
  inputChange(e){
    this.setData({inputVal: e.detail.value})
  },

  onShow(){
    wx.showToast({
      title: '加载数据',
    })
  },

  /**
   * 退回上一页
   */
  toBackClick: function() {
    wx.navigateBack({})
  },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function(e) {
    wx.showToast({
      title: '加载数据',
    })
    console.debug("下拉")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function(e) {
    wx.showToast({
      title: '加载数据',
    })
    console.debug("上拉")
  },


})
